package utils;

import entity.News;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * Created by 梅晨 on 2017/7/20.
 */
public class IOUtils {
    private static Logger logger = Logger.getLogger(IOUtils.class);
    /**
     * 从文件夹中获取新闻的路径以及类别（1表示乐观，2表示悲观）
     * @param dirPath 新闻存在的文件夹所在的路径
     * @return  路径及对应文章类别的map对
     */
    public static HashMap<String,Integer> getFilePathClassMap(String dirPath,String mapPath)throws IOException{
        HashMap<String,Integer> map = new HashMap<String, Integer>();
        HashMap<String,Integer> claIntMap = new HashMap<String, Integer>();
        File dir = new File(dirPath);
        if(dir.isDirectory()){
            logger.info("正在读入文件名数据");
            File[] files = dir.listFiles();
            for(File file : files){
                if(file.isFile()){
                    map.put(file.getAbsolutePath(),1);
                }else if(file.isDirectory()){
                    File[] subfiles = file.listFiles();
                    String cla  = file.getName();
                    int tag;
                    if(claIntMap.containsKey(cla)){
                        tag = claIntMap.get(cla);
                    }else{
                        claIntMap.put(cla,claIntMap.size() + 1);
                        tag = claIntMap.size();
                    }
//                    int tag = Integer.valueOf(file.getName());
                    for(File f : subfiles){
                        map.put(f.getAbsolutePath(),tag);
                    }
                }else {
                    logger.info("file 类型错误");
                    return null;
                }
            }
        }else{
            logger.info("输入必须是文件夹");
            return null;
        }
        if(mapPath != null) saveMap(claIntMap,mapPath);
        return map;
    }

    /**
     * 读取新闻文件中的文本内容
     * @param filePath 新闻的文件路径
     * @return string类型的文本
     */
    public static String getFileContent(String filePath)throws IOException{
        File file = new File(filePath);
        InputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        String str = "";
        while((str = br.readLine()) != null){
            sb.append(str);
        }
        return sb.toString();
    }

    public static List<String> getFileLines(String filePath)throws IOException{
        List<String> result = new ArrayList<String>();
        File file = new File(filePath);
        InputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        BufferedReader br = new BufferedReader(isr);
        String str = "";
        while ((str = br.readLine()) != null){
            result.add(str);
        }
        return result;
    }

    /**
     * 将给定的list按行保存到指定的路径中
     * @param contents
     * @param path
     */
    public static void saveFile(List<String> contents,String path)throws IOException{
        File file = new File(path);
        FileWriter writer = new FileWriter(file);
        for(String s : contents){
            String str = s + "\r\n";
            writer.write(str);
        }
        writer.close();
    }

    /**
     * 读取由libsvm分类得到的文件中的分类结果
     * @param path
     * @return
     * @throws IOException
     */
    public static List<Integer> readClassId(String path)throws IOException{
        List<Integer> list = new ArrayList<Integer>();
        File file = new File(path);
        InputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        String str = "";
        while((str = br.readLine()) != null){
            list.add(Float.valueOf(str).intValue());
        }
        return list;
    }

    /**
     * 将新闻按不同的类别存放到不同的文件夹中
     * @param news
     * @param clas
     * @param path
     */
    public static void saveByClass(List<News> news, HashMap<Integer,String> clas,String path) {
        //create all directories
        File file = new File(path);
        if (!file.exists()) file.mkdir();
        for (int i : clas.keySet()) {
            String cla = clas.get(i);
            String dirPath = path + "//" + cla;
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
        for (int i = 0; i < news.size(); i++) {
            String srcPath = news.get(i).getTitle();
            String content = news.get(i).getContent();
            String className = news.get(i).getEmotion();
            String[] ss = srcPath.split("\\\\");
            String title = ss[ss.length - 1];
            String articlePath = path + "//" + className + "//" + title;
            try {
                FileWriter writer = new FileWriter(new File(articlePath));
                writer.write(content);
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 将map键值对存到指定的文件中
     * @param map
     * @param mapPath
     * @throws IOException
     */
    public static void saveMap(HashMap<String,Integer> map,String mapPath)throws IOException{
        File file = new File(mapPath);
        FileWriter writer = new FileWriter(file);
        for(String s : map.keySet()){
            String str = s + ":" + map.get(s) + '\n';
            writer.write(str);
        }
        writer.close();
    }

    /**
     * 将键值对从文件中读出并返回hashmap
     * @param mapPath
     * @return
     * @throws IOException
     */
    public static HashMap<Integer,String> readMap(String mapPath)throws IOException{
        HashMap<Integer,String> map = new HashMap<Integer,String>();
        File file = new File(mapPath);
        InputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        BufferedReader br = new BufferedReader(isr);
        String str = "";
        while((str = br.readLine()) != null){
            String[] strs = str.split(":");
            map.put(Integer.valueOf(strs[1]),strs[0]);
        }
        return map;
    }

}
